package com.example.app.page;

import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.app.R;
import com.example.app.config.RetrofitClient;
import com.example.app.manager.TokenManager;

public class ProfileFragment extends Fragment {

    private TextView tvUsername;
    private TextView tvEmail;

    private TextView tvUserId;
    private TokenManager tokenManager;

    private RetrofitClient retrofitClient;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.profile, container, false);

        // 初始化视图
        tvUsername = view.findViewById(R.id.tv_username);
        tvEmail = view.findViewById(R.id.tv_email);
        tvUserId = view.findViewById(R.id.tv_user_id);
        View btnLogout = view.findViewById(R.id.btn_logout);

        // 初始化TokenManager
        retrofitClient = RetrofitClient.getInstance((Application) requireContext().getApplicationContext());
        tokenManager = retrofitClient.getTokenManager();

        // 从数据库获取用户信息并设置到视图上
        loadUserInfo();

        // 设置退出登录按钮的点击事件
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });

        return view;
    }

    private void loadUserInfo() {
        System.out.println(tokenManager.getUsername());
        tvUsername.setText(tokenManager.getUsername());
        tvEmail.setText(tokenManager.getEmail());
        tvUserId.setText(tokenManager.getUserId());
    }

    private void logout() {
        // 清除Token和用户信息
        tokenManager.clearAllData();

        // 跳转到登录页面
        Intent intent = new Intent(requireContext(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        requireActivity().finish();
    }
}